package com.yy.bootdemo.security.filter;

import com.alibaba.fastjson.JSON;
import com.yy.bootdemo.security.UserDetailsServiceImpl;
import com.yy.bootdemo.security.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author codermy
 * @createTime 2020/7/30
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private JwtUtils jwtUtils;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        //拿到requset中的head
        String authHeader = request.getHeader(this.tokenHeader);
      //  boolean bl= authHeader.startsWith(this.tokenHead);
       // if (authHeader != null && bl) {
        if (authHeader != null) {
            // The part after "Bearer "
          //  String authToken = authHeader.substring(this.tokenHead.length());
            //解析token获取用户名
           // String username = jwtUtils.getUserNameFromToken(authToken);
            String username1 = jwtUtils.getUserNameFromToken(authHeader);
            log.info("checking username:{}", username1);

            Map<String,Object> map= JSON.parseObject(username1, Map.class);
            String username=map.get("nickname").toString();
            SecurityContext SecurityContext= SecurityContextHolder.getContext() ;
            Authentication authentication1= SecurityContextHolder.getContext().getAuthentication() ;
            if (username != null) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                if (userDetails != null) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    log.info("authenticated user:{}", username);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);

    }
    }

